import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import http from '@/common/http';
import { Dialog } from 'mand-mobile';
import Loading from '@/components/loading';
import Moment from 'moment';
function pySegSort(arr) {
  var letters = '*ABCDEFGHJKLMNOPQRSTWXYZ'.split('');
  var zh = '阿吧嚓哒妸发旮哈讥咔垃妈拏噢妑七呥扨它穵夕丫帀'.split('');
  var segs = [];
  var curr;
  letters.forEach(function(item, i) {
    curr = {
      letter: item,
      data: []
    };
    arr.forEach(function(obj) {
      let p = pinyinUtil.getFirstLetter(obj.name[0]);
      if (item === p) {
        curr.data.push(obj);
      }
    });
    if (curr.data.length) {
      segs.push(curr);
    }
  });
  return segs;
}
function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
function noServerDialog() {
  Dialog.alert({
    title: '错误',
    content: '无法连接到服务器',
    confirmText: '确定'
  });
}
function responseError(message) {
  Dialog.alert({
    title: '错误',
    content: message,
    confirmText: '确定'
  });
}
function getCitysFromAMap() {
  let citys = [];
  return new Promise((resolve, reject) => {
    AMap.plugin('AMap.DistrictSearch', () => {
      const districtSearch = new AMap.DistrictSearch({
        // 关键字对应的行政区级别，country表示国家
        level: 'country',
        //  显示下级行政区级数，1表示返回下一级行政区
        subdistrict: 2
      });
      // 搜索所有省/直辖市信息
      districtSearch.search('中国', (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          if (
            result.districtList instanceof Array &&
            result.districtList.length > 0
          ) {
            const provinces = result.districtList[0].districtList;
            if (provinces instanceof Array && provinces.length > 0) {
              provinces.forEach(province => {
                if (
                  province.districtList instanceof Array &&
                  province.districtList.length > 0
                ) {
                  citys = citys.concat(province.districtList);
                }
              });
              resolve(citys);
            } else {
              reject(new Error('无法获取城市信息' + status));
            }
          } else {
            reject(new Error('无法获取城市信息' + status));
          }
        } else {
          reject(new Error('无法获取城市信息' + status));
        }
      });
    });
  });
}
/**
 *
 * @param {*} url URL地址
 * @param {*} params 需要传的参数
 * @param {*} commit commit对象
 * @param {*} commitString commit方法名，设置为null则禁用commit
 * @param {*} hasLoading 是否需要展示全屏Loading,默认展示
 */
async function sendCommonPost(
  url,
  params,
  commit = null,
  commitString = null,
  hasLoading = true
) {
  if (hasLoading) {
    Loading.show();
  }
  const res = await http.post(url, params).catch(reason => {
    noServerDialog();
    return;
  });
  if (hasLoading) {
    Loading.hide();
  }
  if (res) {
    if (res.data.code === '000000') {
      if (commit && commitString) {
        commit(commitString, res.data.data);
      }
      return res.data.data;
    } else {
      responseError(res.data.msg);
      return new Error(res.data.msg);
    }
  } else {
    noServerDialog();
    return new Error('无法连接到服务器');
  }
}
const defaultState = () => {
  return {
    hitchCitys: null,
    sortedHitchCitys: null,
    hitchUserInfo: null,
    historyStartPositions: [],
    historyEndPositions: [],
    commonPlaces: null,
    gotoWorkInfo: null,
    gotoHomeInfo: null,
    standbyOrders: [],
    timePickerData: null,
    costInfo: null,
    orderInfo: null,
    fixedOrderInfo: null,
    lobbyInfo: null
  };
};
const actions = {
  async getHitchCitys({ commit }) {
    // 获取顺风车开通城市
    Loading.show();
    await getCitysFromAMap()
      .then(citys => {
        commit('setHitchCitys', citys);
      })
      .catch(reason => {
        Dialog.alert({
          title: '错误',
          content: reason.message,
          confirmText: '确定'
        });
      });
    Loading.hide();
  },
  async getHitchCityInfoById({ commit }, cityId) {
    // 根据城市ID获取顺风车城市信息
    return await sendCommonPost(
      'pakj/hitchCity/getHitchCityById',
      { cityId: cityId },
      commit,
      'setHitchCityInfo'
    );
  },
  async getHitchUserInfo({ commit }, userId) {
    // 获取顺风车用户信息
    return await sendCommonPost(
      'pakj/hitchUser/getHitchUser',
      { userId: userId },
      commit,
      'setHitchUserInfo'
    );
  },
  async getStandbyOrders({ commit }) {
    return await sendCommonPost(
      'pakj/hitchOrder/getMyOrder',
      { type: '1', pageSize: '5', pageNo: '0' },
      commit,
      'setStandbyOrders'
    );
  },
  async getHistoryStartPositions({ commit }) {
    return await sendCommonPost(
      'pakj/hitchOrder/getHistoryPst',
      { type: '1', pstType: '1' },
      commit,
      'setHistoryStartPosition'
    );
  },
  async getHistoryEndPositions({ commit }) {
    return await sendCommonPost(
      'pakj/hitchOrder/getHistoryPst',
      { type: '1', pstType: '2' },
      commit,
      'setHistoryEndPosition'
    );
  },
  async getCommonPlaces({ commit }, userId) {
    return await sendCommonPost(
      'pakj/hitchUser/getCommuteLine',
      { type: '1', userId: userId, getType: '1' },
      commit,
      'setCommonPlaces'
    );
  },
  async getAdsorptionInfo({ commit }, info) {
    let params = {
      type: info.isStart ? '1' : '2',
      lnglat: encryptByDESModeEBC(info.coord)
    };
    return await sendCommonPost('pakj/hitchCity/getHitchCity', params);
  },
  async getTimePickerData({ commit }, cityId) {
    return await sendCommonPost(
      'pakj/hitchCity/getOrderTime',
      { cityId: cityId },
      commit,
      'setTimePickerData'
    );
  },
  async getCostInfo({ commit }, params) {
    return await sendCommonPost(
      'pakj/hitchOrder/getHitchCityEstPrice',
      params,
      commit,
      'setCostInfo'
    );
  },
  async createOrder({ commit }, params) {
    return await sendCommonPost(
      'pakj/hitchOrder/createOrder',
      params,
      commit,
      'setOrderInfo'
    );
  },
  async getLobbyInfo({ commit }, orderNo) {
    return await sendCommonPost(
      'pakj/hitchOrder/getSimilarDriver',
      { orderNo: orderNo },
      commit,
      'setLobbyInfo'
    );
  },
  async getOrderById({ commit }, orderNo) {
    return await sendCommonPost(
      'pakj/hitchOrder/getHitchOrder',
      { orderNo: orderNo },
      commit,
      'setOrderInfo'
    );
  },
  async submitCommonPlaces({ commit }, params) {
    return await sendCommonPost('pakj/hitchUser/saveCommuteLine', params);
  },
  async cancelOrder({ commit }, orderNo) {
    let dutyInfo = await sendCommonPost('pakj/hitchOrder/getCancelOrderDuty', {
      type: '1',
      orderNo: orderNo
    });
    return await sendCommonPost('pakj/hitchOrder/cancelOrder', {
      type: '1',
      orderNo: orderNo,
      duty: dutyInfo.duty
    });
  },
  async sendOrderInvitation({ commit }, params) {
    return await sendCommonPost('pakj/hitchOrder/sendOrderInvitation', params);
  },
  async updateRedMoney({ commit }, params) {
    return await sendCommonPost('pakj/hitchOrder/updateRedMoney', params);
  }
};
const getters = {
  hitchCitys(state) {
    return state.hitchCitys;
  },
  sortedHitchCitys(state) {
    return state.sortedHitchCitys;
  },
  hitchUserInfo(state) {
    return state.hitchUserInfo;
  },
  commonPlaces(state) {
    return state.commonPlaces;
  },
  gotoHomeInfo(state) {
    return state.gotoHomeInfo;
  },
  gotoWorkInfo(state) {
    return state.gotoWorkInfo;
  },
  standbyOrders(state) {
    return state.standbyOrders;
  },
  historyPositions(state) {
    return state.historyPositions;
  },
  timePickerData(state) {
    return state.timePickerData;
  },
  costInfo(state) {
    return state.costInfo;
  },
  orderInfo(state) {
    return state.orderInfo;
  },
  fixedOrderInfo(state) {
    return state.fixedOrderInfo;
  },
  lobbyInfo(state) {
    return state.lobbyInfo;
  }
};
const mutations = {
  setHitchCitys(state, citys) {
    state.hitchCitys = citys;
    if (citys instanceof Array) {
      if (citys.length > 0) {
        state.sortedHitchCitys = pySegSort(citys);
      }
    }
  },
  setHitchUserInfo(state, info) {
    state.hitchUserInfo = info;
  },
  setStandbyOrders(state, orders) {
    state.standbyOrders = orders;
  },
  setHistoryStartPosition(state, positions) {
    state.historyStartPositions = positions;
  },
  setHistoryEndPosition(state, positions) {
    state.historyEndPositions = positions;
  },
  setCommonPlaces(state, places) {
    if (!places) {
      return;
    }
    const homePositionInfo = {
      address: {
        stationName: places.originShortAddress,
        position: places.originLongAddress,
        coordinate: decryptByDESModeEBC(places.originLngLat).split(',')
      },
      city: {
        allowMulFlag: places.aallowMulFlag,
        cityId: places.originCityId,
        cityName: places.originCityName,
        orderAutoTime: places.aorderAutoTime,
        orderRemarks: places.aorderRemarks,
        pinOpenFlag: places.apinOpenFlag
      }
    };
    const workPositionInfo = {
      address: {
        stationName: places.destShortAddress,
        position: places.destLongAddress,
        coordinate: decryptByDESModeEBC(places.destLngLat).split(',')
      },
      city: {
        allowMulFlag: places.ballowMulFlag,
        cityId: places.destCityId,
        cityName: places.destCityName,
        orderAutoTime: places.borderAutoTime,
        orderRemarks: places.borderRemarks,
        pinOpenFlag: places.bpinOpenFlag
      }
    };
    let gotoWorkMoment = Moment()
      .hour(parseInt(places.startTimeHour))
      .minute(parseInt(places.startTimeMinute))
      .second(0);
    let gotoHomeMoment = Moment()
      .hour(parseInt(places.endTimeHour))
      .minute(parseInt(places.endTimeMinute))
      .second(0);
    let gotoHomeTimeInfo = {
      type: '2',
      time: gotoHomeMoment.format('x'),
      text: gotoHomeMoment.calendar(),
      hasWaitTime: false
    };
    let gotoWorkTimeInfo = {
      type: '2',
      time: gotoWorkMoment.format('x'),
      text: gotoWorkMoment.calendar(),
      hasWaitTime: false
    };
    const numberInfo = {
      number: places.userNumber,
      isPinche: false
    };
    state.gotoHomeInfo = {
      startInfo: workPositionInfo,
      endInfo: homePositionInfo,
      timeInfo: gotoHomeTimeInfo,
      numberInfo: numberInfo,
      desc: '下班约车',
      flag: 'home'
    };
    state.gotoWorkInfo = {
      startInfo: homePositionInfo,
      endInfo: workPositionInfo,
      timeInfo: gotoWorkTimeInfo,
      numberInfo: numberInfo,
      desc: '上班约车',
      flag: 'work'
    };
    state.commonPlaces = places;
  },
  setTimePickerData(state, data) {
    state.timePickerData = data;
  },
  setCostInfo(state, info) {
    state.costInfo = info;
  },
  setOrderInfo(state, info) {
    state.fixedOrderInfo = {
      startInfo: {
        cityName: info.originCity,
        shortName: info.originShortAddress,
        longName: info.originLongAddress,
        lnglat: decryptByDESModeEBC(info.originLngLat).split(',')
      },
      endInfo: {
        cityName: info.destCityName,
        shortName: info.destShortAddress,
        longName: info.destLongAddress,
        lnglat: decryptByDESModeEBC(info.destLngLat).split(',')
      },
      timeInfo: {
        text: info.departureTimeText, // 时间文本
        timeType: info.timeType, // 时间类型 1、随时出发；2、定点出发
        startTime: info.orderStartTime, // 订单开始时间，乘客上车后司机开始行程的时间
        driveTime: info.driveTime, // 预计行驶时间
        arriveTime: info.driverArriveTime, // 司机到达时间
        earliestTime: info.orderEarliestTime, // 最早出发时间
        endTime: info.orderEndTime, // 订单结束时间
        latestTime: info.orderLatestTime, // 最晚出发时间
        reserveArriveTime: info.reserveArriveTime, //预计到达时间
        reserveTime: info.reserveTime // 预约出发时间
      },
      numberInfo: {
        number: info.orderNumber,
        text: `${info.orderNumber}人${info.orderType == '1' ? '拼车' : '独享'}`
      },
      payInfo: {
        returnHighestAmt: info.returnHighestAmt,
        estimateAmt: info.orderEstimateAmt,
        payType: info.payType, // 支付类型
        payStatus: info.payStatus, //支付状态
        price: info.orderAmt, // 订单金额
        countTime: info.payCountTime // 支付倒计时
      },
      driverInfo: {
        id: info.driverId,
        name: info.driverInfo,
        phone: info.driverPhone,
        avatar: info.driverHeadPhoto,
        nickName: info.driverNickName,
        receiptNumber: info.driverReceiptNumber, // 司机接单数
        creditScore: info.driverCreditScore
      },
      carInfo: {
        color: info.carColour,
        brandModel: info.carBrandModel // 品牌型号
      }
    };
    state.orderInfo = info;
  },
  setLobbyInfo(state, info) {
    state.lobbyInfo = info;
  }
};
const state = defaultState();
export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
};
